{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 1、ChatMessageHistory的使用\n",
    "\n",
    "场景1：记忆存储"
   ],
   "id": "d6ecaa82f6df070e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:16:43.146489Z",
     "start_time": "2025-09-29T03:16:42.201819Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.memory import ChatMessageHistory\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 1、ChatMessageHistory的实例化\n",
    "history= ChatMessageHistory()\n",
    "# 2、添加相关的消息进行存储\n",
    "history.add_user_message(\"你好\")\n",
    "history.add_ai_message(\"很高兴认识你\")\n",
    "\n",
    "# 3、打印存储的消息\n",
    "print(history.messages)"
   ],
   "id": "a9ba6ce0ab9f7",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/miniconda3/envs/pyth310/lib/python3.10/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[HumanMessage(content='你好', additional_kwargs={}, response_metadata={}), AIMessage(content='很高兴认识你', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "场景2：对接LLM",
   "id": "d30748bef71826a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:18:25.371934Z",
     "start_time": "2025-09-29T03:18:23.997206Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 1、获取大模型\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 创建大模型实例\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")"
   ],
   "id": "46d806065ea7cffe",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:18:36.737396Z",
     "start_time": "2025-09-29T03:18:35.665611Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.memory import ChatMessageHistory\n",
    "\n",
    "# 1、ChatMessageHistory的实例化\n",
    "\n",
    "history = ChatMessageHistory()\n",
    "\n",
    "# 2、添加相关的消息进行存储\n",
    "history.add_user_message(\"你好\")\n",
    "history.add_ai_message(\"很高兴认识你\")\n",
    "history.add_user_message(\"帮我计算1 + 2 * 3 = ？\")\n",
    "\n",
    "response = llm.invoke(history.messages)\n",
    "print(response.content)"
   ],
   "id": "137e49aad000cb3c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "根据运算优先级，先进行乘法再进行加法。所以：\n",
      "\n",
      "1 + 2 * 3 = 1 + 6 = 7\n",
      "\n",
      "所以结果是7。\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2、ConversationBufferMemory的使用\n",
    "\n",
    "举例1：以字符串的方式返回存储的信息"
   ],
   "id": "4f386451e4f9b0db"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:22:35.235606Z",
     "start_time": "2025-09-29T03:22:35.228713Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "# 1、ConversationBufferMemory的实例化\n",
    "memory = ConversationBufferMemory()\n",
    "\n",
    "# 2、存储相关的消息\n",
    "# inputs对应的就是用户消息，outputs对应的就是ai消息\n",
    "memory.save_context(inputs={\"human\": \"你好，我叫小明\"},outputs={\"ai\": \"很高兴认识你\"})\n",
    "memory.save_context(inputs={\"input\": \"帮我回答一下1+2*3=?\"}, outputs={\"output\": \"7\"})\n",
    "\n",
    "# 3、获取存储的信息\n",
    "#说明：返回的字典结构的key叫history.\n",
    "print(memory.load_memory_variables({}))"
   ],
   "id": "fd5e30fdf4627efe",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': 'Human: 你好，我叫小明\\nAI: 很高兴认识你\\nHuman: 帮我回答一下1+2*3=?\\nAI: 7'}\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：以消息列表的方式返回存储的信息",
   "id": "8ba27e9a5aaa0f20"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:23:57.002494Z",
     "start_time": "2025-09-29T03:23:56.994522Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "# 1、ConversationBufferMemory的实例化\n",
    "memory = ConversationBufferMemory(return_messages=True)\n",
    "\n",
    "# 2、存储相关的消息\n",
    "# inputs对应的就是用户消息，outputs对应的就是ai消息\n",
    "memory.save_context(inputs={\"human\": \"你好，我叫小明\"}, outputs={\"ai\": \"很高兴认识你\"})\n",
    "memory.save_context(inputs={\"input\": \"帮我回答一下1+2*3=?\"}, outputs={\"output\": \"7\"})\n",
    "\n",
    "# 3、获取存储的信息\n",
    "#返回消息列表的方式1：\n",
    "print(memory.load_memory_variables({}))\n",
    "\n",
    "print(\"\\n\")\n",
    "\n",
    "#返回消息列表的方式2：\n",
    "print(memory.chat_memory.messages)\n",
    "#说明：返回的字典结构的key叫history."
   ],
   "id": "c8b804892b967d0a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': [HumanMessage(content='你好，我叫小明', additional_kwargs={}, response_metadata={}), AIMessage(content='很高兴认识你', additional_kwargs={}, response_metadata={}), HumanMessage(content='帮我回答一下1+2*3=?', additional_kwargs={}, response_metadata={}), AIMessage(content='7', additional_kwargs={}, response_metadata={})]}\n",
      "\n",
      "\n",
      "[HumanMessage(content='你好，我叫小明', additional_kwargs={}, response_metadata={}), AIMessage(content='很高兴认识你', additional_kwargs={}, response_metadata={}), HumanMessage(content='帮我回答一下1+2*3=?', additional_kwargs={}, response_metadata={}), AIMessage(content='7', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：结合大模型、提示词模板的使用（PromptTemplate）",
   "id": "6ddd1a97cad15100"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:25:17.937451Z",
     "start_time": "2025-09-29T03:25:17.017914Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.chains.llm import LLMChain\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "\n",
    "# 1、创建大模型实例\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 2、提供提示词模板\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"\"\"\n",
    "    你可以与人类对话。\n",
    "\n",
    "当前对话历史: {history}\n",
    "\n",
    "人类问题: {question}\n",
    "\n",
    "回复:\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "# 3、提供memory实例\n",
    "memory = ConversationBufferMemory()\n",
    "\n",
    "# 4、提供Chain\n",
    "chain = LLMChain(llm=llm, prompt=prompt_template, memory=memory)\n",
    "\n",
    "response = chain.invoke({\"question\": \"你好，我的名字叫小明\"})\n",
    "print(response)"
   ],
   "id": "f52cff8500bf3e42",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/9p/r71fhhs11052m2r7x4gfc5b80000gn/T/ipykernel_52024/2198948480.py:25: LangChainDeprecationWarning: The class `LLMChain` was deprecated in LangChain 0.1.17 and will be removed in 1.0. Use :meth:`~RunnableSequence, e.g., `prompt | llm`` instead.\n",
      "  chain = LLMChain(llm=llm, prompt=prompt_template, memory=memory)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '你好，我的名字叫小明', 'history': '', 'text': '你好，小明！很高兴认识你。有什么我可以帮助你的吗？'}\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:26:04.579225Z",
     "start_time": "2025-09-29T03:26:03.394649Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = chain.invoke({\"question\": \"我叫什么名字呢？\"})\n",
    "print(response)"
   ],
   "id": "2ec52e037fb257f0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '我叫什么名字呢？', 'history': 'Human: 你好，我的名字叫小明\\nAI: 你好，小明！很高兴认识你。有什么我可以帮助你的吗？', 'text': '你叫小明！很高兴再次见到你，小明。有什么我可以帮助你的吗？'}\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例4：基于举例3，显式的设置meory的key的值",
   "id": "aa0a1fe8ecca0b64"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:27:01.835396Z",
     "start_time": "2025-09-29T03:27:00.529452Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.chains.llm import LLMChain\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "\n",
    "# 1、创建大模型实例\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 2、提供提示词模板\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"\"\"\n",
    "    你可以与人类对话。\n",
    "\n",
    "当前对话历史: {chat_history}\n",
    "\n",
    "人类问题: {question}\n",
    "\n",
    "回复:\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "# 3、提供memory实例\n",
    "memory = ConversationBufferMemory(memory_key=\"chat_history\")\n",
    "\n",
    "# 4、提供Chain\n",
    "chain = LLMChain(llm=llm, prompt=prompt_template, memory=memory)\n",
    "\n",
    "response = chain.invoke({\"question\": \"你好，我的名字叫小明\"})\n",
    "print(response)"
   ],
   "id": "c8b1e1219bcf17b5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '你好，我的名字叫小明', 'chat_history': '', 'text': '你好，小明！很高兴认识你。有什么我可以帮助你的吗？'}\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:27:22.374438Z",
     "start_time": "2025-09-29T03:27:21.640956Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "response = chain.invoke({\"question\": \"我叫什么名字呢？\"})\n",
    "print(response)"
   ],
   "id": "e95868cc7f253074",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '我叫什么名字呢？', 'chat_history': 'Human: 你好，我的名字叫小明\\nAI: 你好，小明！很高兴认识你。有什么我可以帮助你的吗？', 'text': '你的名字是小明！很高兴再次见到你，小明。还有其他想聊的吗？'}\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例5：结合大模型、提示词模板的使用（ChatPromptTemplate）",
   "id": "38bfbbdcf4d2968c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:30:50.870220Z",
     "start_time": "2025-09-29T03:30:49.865685Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 1.导入相关包\n",
    "from langchain_core.messages import SystemMessage\n",
    "from langchain.chains.llm import LLMChain\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "from langchain_core.prompts import MessagesPlaceholder,ChatPromptTemplate,HumanMessagePromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "\n",
    "# 2.创建LLM\n",
    "llm = ChatOpenAI(model_name='gpt-4o-mini')\n",
    "\n",
    "# 3.创建Prompt\n",
    "prompt = ChatPromptTemplate.from_messages([\n",
    "    (\"system\",\"你是一个与人类对话的机器人。\"),\n",
    "    MessagesPlaceholder(variable_name='history'),\n",
    "    (\"human\",\"问题：{question}\")\n",
    "])\n",
    "\n",
    "# 4.创建Memory\n",
    "memory = ConversationBufferMemory(return_messages=True)\n",
    "# 5.创建LLMChain\n",
    "llm_chain = LLMChain(prompt=prompt,llm=llm, memory=memory)\n",
    "\n",
    "# 6.调用LLMChain\n",
    "res1 = llm_chain.invoke({\"question\": \"中国首都在哪里？\"})\n",
    "print(res1,end=\"\\n\\n\")"
   ],
   "id": "5c688729234a6a7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '中国首都在哪里？', 'history': [HumanMessage(content='中国首都在哪里？', additional_kwargs={}, response_metadata={}), AIMessage(content='中国的首都在北京。', additional_kwargs={}, response_metadata={})], 'text': '中国的首都在北京。'}\n",
      "\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:31:20.670952Z",
     "start_time": "2025-09-29T03:31:19.813641Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "res2 = llm_chain.invoke({\"question\": \"我刚刚问了什么\"})\n",
    "print(res2)"
   ],
   "id": "fee7ad83c5056fda",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '我刚刚问了什么', 'history': [HumanMessage(content='中国首都在哪里？', additional_kwargs={}, response_metadata={}), AIMessage(content='中国的首都在北京。', additional_kwargs={}, response_metadata={}), HumanMessage(content='我刚刚问了什么', additional_kwargs={}, response_metadata={}), AIMessage(content='你刚刚问了中国的首都在哪里。', additional_kwargs={}, response_metadata={})], 'text': '你刚刚问了中国的首都在哪里。'}\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3、ConversationChain的使用\n",
    "\n",
    "举例1：以PromptTemplate为例"
   ],
   "id": "9929fd272506bd5c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:33:42.489230Z",
     "start_time": "2025-09-29T03:33:41.666658Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.chains.conversation.base import ConversationChain\n",
    "from langchain.chains.llm import LLMChain\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "\n",
    "# 1、创建大模型实例\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 2、提供提示词模板\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"\"\"\n",
    "    你可以与人类对话。\n",
    "\n",
    "当前对话历史: {history}\n",
    "\n",
    "人类问题: {input}\n",
    "\n",
    "回复:\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "# # 3、提供memory实例\n",
    "# memory = ConversationBufferMemory()\n",
    "#\n",
    "# # 4、提供Chain\n",
    "# chain = LLMChain(llm=llm, prompt=prompt_template, memory=memory)\n",
    "\n",
    "# 3、创建ConversationChain的实例\n",
    "chain = ConversationChain(llm = llm, prompt=prompt_template)\n",
    "\n",
    "response = chain.invoke({\"input\": \"你好，我的名字叫小明\"})\n",
    "print(response)"
   ],
   "id": "b9113e61e410f2e",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/9p/r71fhhs11052m2r7x4gfc5b80000gn/T/ipykernel_52024/2195652100.py:29: LangChainDeprecationWarning: The class `ConversationChain` was deprecated in LangChain 0.2.7 and will be removed in 1.0. Use :class:`~langchain_core.runnables.history.RunnableWithMessageHistory` instead.\n",
      "  chain = ConversationChain(llm = llm, prompt=prompt_template)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'input': '你好，我的名字叫小明', 'history': '', 'response': '你好，小明！很高兴认识你。有什么我可以帮助你的吗？'}\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:34:00.372013Z",
     "start_time": "2025-09-29T03:33:59.527534Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "response = chain.invoke({\"input\": \"我的名字叫什么？\"})\n",
    "print(response)"
   ],
   "id": "d1c8379e8fc23f46",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'input': '我的名字叫什么？', 'history': 'Human: 你好，我的名字叫小明\\nAI: 你好，小明！很高兴认识你。有什么我可以帮助你的吗？', 'response': '你的名字叫小明。你有什么想聊的吗？'}\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：使用默认提供的提示词模板",
   "id": "40c857f3de67ab04"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:35:29.454135Z",
     "start_time": "2025-09-29T03:35:28.352039Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.chains.conversation.base import ConversationChain\n",
    "from langchain.chains.llm import LLMChain\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "\n",
    "# 1、创建大模型实例\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 2、提供提示词模板\n",
    "# prompt_template = PromptTemplate.from_template(\n",
    "#     template=\"\"\"\n",
    "#     你可以与人类对话。\n",
    "#\n",
    "# 当前对话历史: {history}\n",
    "#\n",
    "# 人类问题: {input}\n",
    "#\n",
    "# 回复:\n",
    "# \"\"\"\n",
    "# )\n",
    "\n",
    "# # 3、提供memory实例\n",
    "# memory = ConversationBufferMemory()\n",
    "#\n",
    "# # 4、提供Chain\n",
    "# chain = LLMChain(llm=llm, prompt=prompt_template, memory=memory)\n",
    "\n",
    "# 3、创建ConversationChain的实例（内部提供了默认的提示词模板。而此模板中的变量是{input}、{history}\n",
    "chain = ConversationChain(llm = llm)\n",
    "\n",
    "response = chain.invoke({\"input\": \"你好，我的名字叫小明\"})\n",
    "print(response)"
   ],
   "id": "5ea5f0e83467e5a8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'input': '你好，我的名字叫小明', 'history': '', 'response': '你好，小明！很高兴认识你！我是一个人工智能助手，随时准备帮助你。不知道你今天有什么想聊的呢？或者有没有什么问题想问我？'}\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:35:50.326402Z",
     "start_time": "2025-09-29T03:35:49.214539Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "response = chain.invoke({\"input\": \"我的名字叫什么？\"})\n",
    "print(response)"
   ],
   "id": "b06842bfa7b7f30d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'input': '我的名字叫什么？', 'history': 'Human: 你好，我的名字叫小明\\nAI: 你好，小明！很高兴认识你！我是一个人工智能助手，随时准备帮助你。不知道你今天有什么想聊的呢？或者有没有什么问题想问我？', 'response': '你的名字叫小明！我记得你刚刚告诉我了。你还有其他想分享的事情吗？或者有什么话题想要讨论吗？'}\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 4、ConversationBufferWindowMemory的使用\n",
    "\n",
    "举例1："
   ],
   "id": "78a7d60645cc2c7c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:36:28.402084Z",
     "start_time": "2025-09-29T03:36:28.395868Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "# 1.导入相关包\n",
    "from langchain.memory import ConversationBufferWindowMemory\n",
    "\n",
    "# 2.实例化ConversationBufferWindowMemory对象，设定窗口阈值\n",
    "memory = ConversationBufferWindowMemory(k=1)\n",
    "# 3.保存消息\n",
    "memory.save_context({\"input\": \"你好\"}, {\"output\": \"怎么了\"})\n",
    "memory.save_context({\"input\": \"你是谁\"}, {\"output\": \"我是AI助手\"})\n",
    "memory.save_context({\"input\": \"你的生日是哪天？\"}, {\"output\": \"我不清楚\"})\n",
    "# 4.读取内存中消息（返回消息内容的纯文本）\n",
    "print(memory.load_memory_variables({}))"
   ],
   "id": "dee422815414be13",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': 'Human: 你的生日是哪天？\\nAI: 我不清楚'}\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/9p/r71fhhs11052m2r7x4gfc5b80000gn/T/ipykernel_52024/3455059608.py:5: LangChainDeprecationWarning: Please see the migration guide at: https://python.langchain.com/docs/versions/migrating_memory/\n",
      "  memory = ConversationBufferWindowMemory(k=1)\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：返回消息构成的上下文记忆",
   "id": "75235d7afe79db82"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:37:41.141478Z",
     "start_time": "2025-09-29T03:37:41.134843Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain.memory import ConversationBufferWindowMemory\n",
    "\n",
    "# 2.实例化ConversationBufferWindowMemory对象，设定窗口阈值\n",
    "memory = ConversationBufferWindowMemory(k=2, return_messages=True)\n",
    "# 3.保存消息\n",
    "memory.save_context({\"input\": \"你好\"}, {\"output\": \"怎么了\"})\n",
    "memory.save_context({\"input\": \"你是谁\"}, {\"output\": \"我是AI助手小智\"})\n",
    "memory.save_context({\"input\": \"初次对话，你能介绍一下你自己吗？\"}, {\"output\": \"当然可以了。我是一个无所不能的小智。\"})\n",
    "# 4.读取内存中消息（返回消息内容的纯文本）\n",
    "print(memory.load_memory_variables({}))"
   ],
   "id": "ff4d593ec3077572",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': [HumanMessage(content='你是谁', additional_kwargs={}, response_metadata={}), AIMessage(content='我是AI助手小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='初次对话，你能介绍一下你自己吗？', additional_kwargs={}, response_metadata={}), AIMessage(content='当然可以了。我是一个无所不能的小智。', additional_kwargs={}, response_metadata={})]}\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：结合llm、chain的使用",
   "id": "efaeb22ce5c1fb77"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:39:25.464411Z",
     "start_time": "2025-09-29T03:39:21.992655Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.memory import ConversationBufferWindowMemory\n",
    "# 1.导入相关包\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "from langchain.chains.llm import LLMChain\n",
    "\n",
    "# 2.定义模版\n",
    "template = \"\"\"以下是人类与AI之间的友好对话描述。AI表现得很健谈，并提供了大量来自其上下文的具体细节。如果AI不知道问题的答案，它会表示不知道。\n",
    "\n",
    "当前对话：\n",
    "{history}\n",
    "Human: {question}\n",
    "AI:\"\"\"\n",
    "\n",
    "# 3.定义提示词模版\n",
    "prompt_template = PromptTemplate.from_template(template)\n",
    "\n",
    "# 4.创建大模型\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 5.实例化ConversationBufferWindowMemory对象，设定窗口阈值\n",
    "memory = ConversationBufferWindowMemory(k=1)\n",
    "\n",
    "# 6.定义LLMChain\n",
    "conversation_with_summary = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=prompt_template,\n",
    "    memory=memory,\n",
    "    #verbose=True,\n",
    ")\n",
    "\n",
    "# 7.执行链（第一次提问）\n",
    "respon1 = conversation_with_summary.invoke({\"question\":\"你好，我是孙小空\"})\n",
    "print(respon1)\n",
    "# 8.执行链（第二次提问）\n",
    "respon2 =conversation_with_summary.invoke({\"question\":\"我还有两个师弟，一个是猪小戒，一个是沙小僧\"})\n",
    "print(respon2)\n",
    "# 9.执行链（第三次提问）\n",
    "respon3 =conversation_with_summary.invoke({\"question\":\"我今年高考，竟然考上了1本\"})\n",
    "print(respon3)\n",
    "# 10.执行链（第四次提问）\n",
    "respon4 =conversation_with_summary.invoke({\"question\":\"我叫什么名字？\"})\n",
    "print(respon4)"
   ],
   "id": "d244a72ee88b0ffa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '你好，我是孙小空', 'history': '', 'text': '你好，孙小空！很高兴认识你。有任何想聊的话题吗？或者你有什么问题想问我？'}\n",
      "{'question': '我还有两个师弟，一个是猪小戒，一个是沙小僧', 'history': 'Human: 你好，我是孙小空\\nAI: 你好，孙小空！很高兴认识你。有任何想聊的话题吗？或者你有什么问题想问我？', 'text': '很高兴认识你的师弟们，孙小空！猪小戒和沙小僧名字听起来很有趣。他们的性格或特长是什么呢？你们平时一起做些什么活动？'}\n",
      "{'question': '我今年高考，竟然考上了1本', 'history': 'Human: 我还有两个师弟，一个是猪小戒，一个是沙小僧\\nAI: 很高兴认识你的师弟们，孙小空！猪小戒和沙小僧名字听起来很有趣。他们的性格或特长是什么呢？你们平时一起做些什么活动？', 'text': '恭喜你考上了1本！这是一个很棒的成就，说明你的努力得到了回报。你选择了哪个专业呢？你对大学生活有什么期待或者计划吗？'}\n",
      "{'question': '我叫什么名字？', 'history': 'Human: 我今年高考，竟然考上了1本\\nAI: 恭喜你考上了1本！这是一个很棒的成就，说明你的努力得到了回报。你选择了哪个专业呢？你对大学生活有什么期待或者计划吗？', 'text': '抱歉，我不知道你的名字。如果你愿意，可以告诉我你的名字！'}\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例4：修改举例3中的参数k",
   "id": "312807d94a3ea404"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-29T03:40:16.003358Z",
     "start_time": "2025-09-29T03:40:11.466654Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.memory import ConversationBufferWindowMemory\n",
    "# 1.导入相关包\n",
    "from langchain_core.prompts.prompt import PromptTemplate\n",
    "from langchain.chains.llm import LLMChain\n",
    "\n",
    "# 2.定义模版\n",
    "template = \"\"\"以下是人类与AI之间的友好对话描述。AI表现得很健谈，并提供了大量来自其上下文的具体细节。如果AI不知道问题的答案，它会表示不知道。\n",
    "\n",
    "当前对话：\n",
    "{history}\n",
    "Human: {question}\n",
    "AI:\"\"\"\n",
    "\n",
    "# 3.定义提示词模版\n",
    "prompt_template = PromptTemplate.from_template(template)\n",
    "\n",
    "# 4.创建大模型\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 5.实例化ConversationBufferWindowMemory对象，设定窗口阈值\n",
    "memory = ConversationBufferWindowMemory(k=3)\n",
    "\n",
    "# 6.定义LLMChain\n",
    "conversation_with_summary = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=prompt_template,\n",
    "    memory=memory,\n",
    "    #verbose=True,\n",
    ")\n",
    "\n",
    "# 7.执行链（第一次提问）\n",
    "respon1 = conversation_with_summary.invoke({\"question\":\"你好，我是孙小空\"})\n",
    "# print(respon1)\n",
    "# 8.执行链（第二次提问）\n",
    "respon2 =conversation_with_summary.invoke({\"question\":\"我还有两个师弟，一个是猪小戒，一个是沙小僧\"})\n",
    "# print(respon2)\n",
    "# 9.执行链（第三次提问）\n",
    "respon3 =conversation_with_summary.invoke({\"question\":\"我今年高考，竟然考上了1本\"})\n",
    "# print(respon3)\n",
    "# 10.执行链（第四次提问）\n",
    "respon4 =conversation_with_summary.invoke({\"question\":\"我叫什么名字？\"})\n",
    "print(respon4)"
   ],
   "id": "64f45eafff656b7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'question': '我叫什么名字？', 'history': 'Human: 你好，我是孙小空\\nAI: 你好，孙小空！很高兴认识你。有什么我可以帮助你的吗？或者你想聊聊什么？\\nHuman: 我还有两个师弟，一个是猪小戒，一个是沙小僧\\nAI: 很高兴听到你提到你的师弟们，孙小空！猪小戒和沙小僧听起来都很有趣。你们之间有什么有趣的故事吗？或者你们在一起做过什么特别的事情？\\nHuman: 我今年高考，竟然考上了1本\\nAI: 哇，恭喜你，孙小空！考上一本大学真是一个了不起的成就！你一定付出了很多努力。你决定上哪所大学了吗？或者你对未来的学习有什么特别的期待吗？', 'text': '你叫孙小空。刚才你提到过你的名字！有什么其他我可以帮助你解答的问题吗？'}\n"
     ]
    }
   ],
   "execution_count": 22
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
